package com.example.javaproject.thread.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintTest {

    private final static Lock lock = new ReentrantLock();
    private final static Condition numberCondition = lock.newCondition();
    private final static Condition chCondition = lock.newCondition();

    private static volatile boolean isNumberPrint = false;


    public static void main(String[] args) {
        new Thread("cThread") {
            private String[] ch = {"A", "B", "C"};

            @Override
            public void run() {
                lock.lock();
                try {
                    for (int i = 0; i < ch.length; i++) {
                        if (!isNumberPrint) {
                            chCondition.await();
                        } else {
                            chCondition.signal();
                        }
                        String number = ch[i];
                        System.out.print(number + ", ");
                        numberCondition.signal();
                        if (i != ch.length - 1) {
                            chCondition.await();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }.start();
        new Thread("numberThread") {
            private String[] numbers = {"1", "2", "3"};

            @Override
            public void run() {
                lock.lock();

                if (!isNumberPrint) {
                    isNumberPrint = true;
                }
                try {
                    for (int i = 0; i < numbers.length; i++) {
                        String number = numbers[i];
                        System.out.print(number + ", ");
                        chCondition.signalAll();
                        if (i != numbers.length - 1) {
                            numberCondition.await();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }.start();
    }
}
